/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from 'react';
import { Spin } from 'antd';
import { connect } from 'dva';
import Link from 'umi/link';
import Exception from '@/components/Exception';

@connect(({ loading, user, setting }) => ({
  currentUser: user.currentUser || {},
  loading: loading.effects['info/getInfo'],
  ...setting,
}))
export default class PermissionLayout extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      enable: true,
    };
  }

  componentDidMount() {
    const {
      currentUser: { roles },
    } = this.props;
    this.getCurrentPermission(roles);
  }

  componentDidUpdate(prevProps) {
    const {
      currentUser: { roles: prevRoles },
    } = prevProps;
    const {
      currentUser: { roles },
    } = this.props;
    if (prevRoles !== roles) {
      this.getCurrentPermission(roles);
    }
  }

  // 获取当前权限，显示不同内容
  getCurrentPermission(roles) {
    if (!roles) return;
    const {
      location: { pathname },
      currentUser: { pid, sub_privilege },
    } = this.props;
    const [, , path = ''] = pathname.match(/(^\/)([a-zA-Z0-9]+)(\/.+)?/) || [];
    // 当pid大于0时说明是子账号，通过sub_privilege字段去判断权限，等于0说明不是子账号，用roles字段判断权限
    const enable =
      pid > 0
        ? sub_privilege.length === 0 || sub_privilege[0] == '*'
          ? true
          : sub_privilege.includes(path.toLocaleLowerCase())
        : roles.length === 0
          ? true
          : roles.includes(path.toLocaleLowerCase());
    this.setState({
      enable,
    });
  }

  render() {
    const { loading, children, options } = this.props;
    const { key } = options;
    const { enable } = this.state;
    return (
      <Fragment>
        <div>
          <Spin spinning={!!loading}>
            {enable ? (
              children
            ) : (
              <Exception
                type="403"
                title="无权使用"
                linkElement={Link}
                desc={
                  <>
                    {key == 'yz' ? (
                      <div>
                        <p>该功能暂未开通，如需使用，请联系快宝公司！</p>
                        <p>服务QQ群：13818443483</p>
                        <p>微信号：kbyz1688</p>
                        <p />
                      </div>
                    ) : null}
                  </>
                }
              />
            )}
          </Spin>
        </div>
      </Fragment>
    );
  }
}
